package com.tledu.spring.controller;

import com.tledu.spring.core.entity.AjaxResult;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Lsj
 * @version 1.0
 * @date 2021/7/5 16:23
 */
@Controller
public class WelcomeController{
    @PostMapping("upload")
    @ResponseBody
    public AjaxResult<Map> upload(MultipartFile file, HttpServletRequest request){
        if (file.isEmpty()) {
            // 为空就不搭理了
            return new AjaxResult<>("图片为空");
        }
        String realpath = "F:";
        System.out.println("realpath:"+realpath);
        String path = "/upload/" + System.currentTimeMillis() + file.getOriginalFilename();
        File destFile = new File(realpath + path);
        // org.apache.commons.io.FileUtils
        try {
            // 第一个参数是文件源的流
            // 第二个参数是到哪去
            FileUtils.copyInputStreamToFile(file.getInputStream(), destFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map map = new HashMap();
        map.put("src", path);
        return new AjaxResult<>(map);
    }
    @PostMapping("testAdd")
    @ResponseBody
    public String testAdd(String text){
        return text;
    }
}
